﻿from django.shortcuts import render, reverse, redirect, HttpResponse


# Create your views here.
def index(request):
    '''首页

    准备工作
    '''
    markdown = """# 反向解析和重定向

链接示例 | 说明
---|---
[reverse](/5/reverse) | reverse
[redirect](/5/redirect) | redirect

## 反向解析

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ title }}</title>
</head>
<body>
    <h2>URL 反向解析</h2>
    <li>多层模板的复用的地址是：{% url '3:two' %}</li>
    <li>user 的地址是: {% url '3:user' %}</li>
    <li>item 的地址是: {% url '3:item' %}</li>
</body>
</html>
```

## 重定向

* 视图

    ```python
    def reverse_handler(request):
        print(reverse('3:index'))
        print(reverse('2:index'))
        return HttpResponse('reverse')

    def redirect_handler(request):
        return redirect(reverse('2:index'))
    ```

* 路由

    ```python
    urlpatterns = [
        ...
        path('reverse', views.reverse_handler),
        path('redirect', views.redirect_handler),
    ]
    ```

"""
    context = {
        'title': 'Home',
        'markdown': markdown,
    }
    return render(request, 'marked.html', context)


def reverse_handler(request):
    print(reverse('3:index'))
    print(reverse('2:index'))
    return HttpResponse('reverse')


def redirect_handler(request):
    return redirect(reverse('2:index'))
